﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace CreatePerformanceCounters
{
    [ExcludeFromCodeCoverage]
    class PerformanceCounterRepository : IPerformanceCounterRepository
    {
        public void Create(List<PerformanceCounterCategory> categories)
        {
            foreach (var item in categories)
            {
                var counterDataColletion = GetCounterCreationDataCollection(item.Counters);
                DeleteCategoryIfExists(item);
                Create(item, counterDataColletion);
            }
        }

        private void Create(PerformanceCounterCategory category,
            CounterCreationDataCollection counters)
        {
            System.Diagnostics.PerformanceCounterCategory.Create(category.Name,
                category.Help,
                (PerformanceCounterCategoryType)category.Type,
                counters);
        }

        private void DeleteCategoryIfExists(PerformanceCounterCategory item)
        {
            if (System.Diagnostics.PerformanceCounterCategory.Exists(item.Name))
            {
                System.Diagnostics.PerformanceCounterCategory.Delete(item.Name);
            }
        }

        private CounterCreationDataCollection GetCounterCreationDataCollection(List<PerformanceCounter> list)
        {
            CounterCreationDataCollection collection = new CounterCreationDataCollection();

            foreach (var item in list)
            {
                collection.Add(GetCounterCreationDataCollection(item));
            }

            return collection;
        }

        private CounterCreationData GetCounterCreationDataCollection(PerformanceCounter item)
        {
            return new CounterCreationData(item.Name, 
                item.Help, 
                (PerformanceCounterType)item.Type);
        }
    }
}
